import os
import time
import traceback

import requests
from PyQt5.QtCore import QThreadPool, QRunnable
from bs4 import BeautifulSoup


def get_num(mh_name):
    # 此方法适用于 全局代理方式代理访问
    proxy_url = "http://127.0.0.1:7890"  # 为本机代理端口及ip
    os.environ['HTTP_PROXY'] = proxy_url
    os.environ['HTTPS_PROXY'] = proxy_url

    cookies = {
        '_ga': 'GA1.1.458481189.1720864625',
        'pid': '4922736',
        '_ga_QB34PY46SE': 'GS1.1.1721012244.3.1.1721013742.0.0.0',
    }

    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
                  'application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'max-age=0',
        'priority': 'u=0, i',
        'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'none',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/126.0.0.0 Safari/537.36',
    }

    response = requests.get(f'https://xn--ihqv6vi6hz9a.jyaaa.top/comic/{mh_name}', cookies=cookies, headers=headers)

    print(response.status_code)
    soup = BeautifulSoup(response.text, 'html.parser')
    a_items = (
        soup.find_all("a", class_="j-chapter-link")
    )
    name_list = []
    for item in a_items:
        name_list.append(item.get('href').replace("/chapter/", ""))
    return name_list


def get_pic(num):
    # 此方法只适用于 其他代理端口 账号密码方式
    proxy = {
        'http': 'http://379557621:idfnnMhpjm@108.165.218.102:50100',
        'https': 'https://379557621:idfnnMhpjm@108.165.218.102:50100',
    },

    # 此方法适用于 全局代理方式代理访问
    proxy_url = "http://127.0.0.1:7890"  # 为本机代理端口及ip
    os.environ['HTTP_PROXY'] = proxy_url
    os.environ['HTTPS_PROXY'] = proxy_url

    cookies = {
        '_ga': 'GA1.1.458481189.1720864625',
        '_ga_QB34PY46SE': 'GS1.1.1720864625.1.1.1720864697.0.0.0',
    }

    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
                  'application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9',
        'priority': 'u=0, i',
        'referer': 'https://xn--ihqv6vi6hz9a.jyaaa.top/comic/3dmori',
        'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/126.0.0.0 Safari/537.36',
    }
    response = requests.get(f'https://xn--ihqv6vi6hz9a.jyaaa.top/chapter/{num}',
                            cookies=cookies,
                            headers=headers,
                            )
    print(response.status_code)
    soup = BeautifulSoup(response.text, 'html.parser')
    a_items = (
        soup.find_all("img", class_="lazy-read")
    )
    pic_list = []
    for item in a_items:
        pic_list.append(item.get('data-original'))
    return pic_list


def download_image(url, fileName, ix, idx):
    """
    下载图片到本地
    :param idx: 下标
    :param ix: 章节
    :param fileName: 存放文件夹
    :param url: 图片的URL
    """
    try:
        # 发送GET请求获取图片
        response = requests.get(url, stream=True)
        mkdirFile(fileName)
        save_path = f"{fileName}/{ix}_{int(time.time() * 10)}_{idx}.jpg"
        # 检查请求是否成功
        if response.status_code == 200:
            # 打开文件以二进制写模式
            with open(save_path, 'wb') as file:
                # 迭代响应内容，并写入文件
                for chunk in response:
                    file.write(chunk)

            # 如果你安装了Pillow库，可以打开图片以验证下载是否成功
            # img = Image.open(save_path)
            # img.show()

            print(f"Image downloaded successfully to {save_path}")
        else:
            print(f"Failed to download image from {url}. Status code: {response.status_code}")

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")


def mkdirFile(fileName):
    # 获取当前目录
    current_directory = os.getcwd()
    # 指定要创建的目录路径
    directory = f"{current_directory}/{fileName}"
    # 使用 os.makedirs 创建目录
    # 如果目录已存在，可以设置 exist_ok=True 来避免引发异常
    try:
        os.makedirs(directory, exist_ok=True)
    except OSError as e:
        print(f"创建目录时发生错误: {e}")


class TaskRunnable(QRunnable):
    def __init__(self, data):
        super(TaskRunnable, self).__init__()
        self.data = data

    def run(self):
        # 这里执行你的任务，处理 self.data
        if self.data is None:
            return
        nums_list = get_num(self.data)
        print(nums_list)
        for ix, num in enumerate(nums_list):
            list_data = get_pic(num)
            for index, a in enumerate(list_data):
                download_image(a, self.data, str(ix + 1), index)


if __name__ == '__main__':
    # 多线程 线程池
    threadpool = QThreadPool()
    threadpool.setMaxThreadCount(20)

    list_total = [
        # "piaoliangmamadeguojiajiayouxi3d"
        # , "wohemamademimiyouxi3d"
        # , "3dcuimianqidiludiyibumuqiangpian"
        # , "3dcuimianqidiludierbuduishepian"
        # , "3dbuzhiqingdefuqiangzhuwogongluemeimu"
        # , "3dmori"
        # , "3dyinmuriji"
        # , "3dxixueguilvchamamadi12ji"
        # , "3dmeimujiaoshifanwaipian"

        # , "3dmamashijianshenjiaolian"
        # , "3dmuzijiaohuan"
        # , "3dyinluandemama"
        # , "3dmamachengliaojialibaomuerxifu"
        # , "3dwodejiaoshimamaqiansuili"
        # , "3dwohemamademimi"
        # , "3dbuaichuanyifudemama"
        # , "3dmamadenaizi"
        # , "3djiaoshimamahenyindangzhijianyinmeimu"

        # "3dbeibierzi"
        # , "3derzideshengriliwu"
        # , "3dwoheerzidemimi"
        # , "3dmihudeerzixunlianpian"
        # , "3dmeimudegouyin"
        # , "3dyinqilisisi"
        # , "3dwodenuwangmuqiang"
        # , "3dwodeluanshi"
        # , "3djiaohuanqizi"
        # , "3dmuqiangdebeipan"
        # , "3dchuquwushanbushiyunyanmu"
        # "3dzhibojianmeishumudejingcaixingshi",
        # "3dlvmukong"
        "3dmamachengliaojialibaomuerxifu"
    ]

    for value in list_total:
        print(f"打印头：{value}")
        runnable = TaskRunnable(value)
        threadpool.start(runnable)
